require "socket"
class ChatServer
	attr_reader :descriptors, :clientcount
	def initialize (port)
		@descriptors = Array::new
		@serverSocket = TCPServer.new("",port)
		@serverSocket.setsockopt(Socket::SOL_SOCKET, Socket::SO_REUSEADDR, 1)
		printf("Chatserver started on port %d\n",port)
		@descriptors.push(@serverSocket)
		@connected = false
		@clientcount = 0
		@runThread = Thread.new{run}
	end #initialize
	
	def run
		while 1
			res = select(@descriptors, nil, nil, nil)
			if res != nil then
				for sock in res[0]
					if sock == @serverSocket then
						accept_new_connection
					else
						if sock.eof? then
							str = sprintf("Client left %s:%s\n",sock.peeraddr[2],sock.peeraddr[1])
							broadcast_string(str,sock)
							sock.close
							@descriptors.delete(sock)
							@clientcount = @clientcount-1
							print "Clientcount"+@clientcount.to_s
						else
							str = sprintf("[%s|%s]: %s",
							sock.peeraddr[2],sock.peeraddr[1],sock.gets())
							broadcast_string(str,sock)
						end
					end
				end
			end
		end
	end #run
	
	
	
	
	def broadcast_string(str,omit_sock)
		@descriptors.each do |clisock|
			if clisock != @serverSocket && clisock != omit_sock
				clisock.write(str)
			end
		end
		print(str)
	end #broadcast_string
	
	def accept_new_connection
		newsock = @serverSocket.accept
		@connected=true
		@clientcount = @clientcount+1
		print "Clientcount"+@clientcount.to_s
		@descriptors.push(newsock)
		newsock.write("You are connected\n")
		str = sprintf("Client joined %s:%s\n",newsock.peeraddr[2], newsock.peeraddr[1])
		broadcast_string(str,newsock)
	end #accept_new_connection
	
	
	
end #server